using UnityEngine;
using System.Collections;

public class AudioManager : MonoBehaviour
{

	public AudioSource audio_source_bg;
	public AudioSource[] audio_sources;
	public float fadeInVel, fadeOutVel;
	public float fadeInAmount, fadeOutAmount;
	public static AudioManager instance;

	void Awake ()
	{
		instance = this;
		DontDestroyOnLoad (gameObject);
	}

	void Start ()
	{
		if (audio_source_bg == null)
			audio_source_bg = gameObject.GetComponent<AudioSource> ();
		
		audio_sources = gameObject.GetComponents<AudioSource> ();

		
	}
	
	void Update ()
	{	
	}

    public void ChangeSpecialCube()
    {
        //StopAllCoroutines();

        StartCoroutine(FadeIn(audio_sources[0]));
        StartCoroutine(FadeIn(audio_sources[1]));
        StartCoroutine(FadeIn(audio_sources[2]));
        StartCoroutine(FadeIn(audio_sources[3]));
        StartCoroutine(FadeIn(audio_sources[4]));
        StartCoroutine(FadeIn(audio_sources[5]));
    }

	public void ChangeAudioChannels (Color color)
	{
        //StopAllCoroutines();

		if (color.r != 1) {
			if (color.r > 0) {

                audio_sources[0].time = audio_sources[2].time;
				StartCoroutine (FadeIn (audio_sources [0]));

			} else {
				//desabilita os canais
				StartCoroutine (FadeOut (audio_sources [0]));
				StartCoroutine (FadeOut (audio_sources [1]));
				
			}
		} else {
            audio_sources[0].time = audio_sources[2].time;
			//dois canais vermelhos
			StartCoroutine (FadeIn (audio_sources [0]));
			StartCoroutine (FadeIn (audio_sources [1]));
			
		}
		
		
		if (color.g != 1) {
			if (color.g > 0) {
				//apenas um canal
				StartCoroutine (FadeIn (audio_sources [2]));
			} else {
				//desabilita os canais
				StartCoroutine (FadeOut (audio_sources [2]));
				StartCoroutine (FadeOut (audio_sources [3]));
				
			}
		} else {
			//dois canais vermelhos
			StartCoroutine (FadeIn (audio_sources [2]));
			StartCoroutine (FadeIn (audio_sources [3]));
			
		}
		
		
		if (color.b != 1) {
			if (color.b > 0) {
				//apenas um canal
				StartCoroutine (FadeIn (audio_sources [4]));
			} else {
				//desabilita os canais
				StartCoroutine (FadeOut (audio_sources [4]));
				StartCoroutine (FadeOut (audio_sources [5]));
				
			}
		} else {
			//dois canais vermelhos
			StartCoroutine (FadeIn (audio_sources [4]));
			StartCoroutine (FadeIn (audio_sources [5]));
			
		}
	}

		
	void StopAudio (AudioSource adSource)
	{
		if (adSource.clip != null)
			adSource.Stop ();
		
	}
	
	void PlayAudio (AudioSource adSource)
	{
		if (adSource.clip != null)
			adSource.Play ();
	
	}
		
	IEnumerator FadeIn (AudioSource audioSource)
	{
		
		while (audioSource.volume < 1) {
				
			audioSource.volume += this.fadeInAmount;
			yield return new WaitForSeconds(1/this.fadeInVel);
		}

	}
	
	IEnumerator FadeOut (AudioSource audioSource)
	{
 	
		while (audioSource.volume > 0) {
				
			audioSource.volume -= this.fadeOutAmount;
			yield return new WaitForSeconds(1/this.fadeOutVel);

		}

	}
	
}
